﻿using System;
using System.Text.RegularExpressions;

namespace SG.Ling.AutoTranslator.NLP
{
    public static class Normalization
    {
        public static char ReplaceWideWithLatin(this char @this)
        {
            switch (@this)
            {
                case '。':
                    return '.';
                case '，':
                    return ',';
                case '！':
                    return '!';
                case '？':
                    return '?';
                case '“':
                    return '"';
                case '…':
                    return '.';
                default:
                    return @this;
            }
        }

        public static string NormalizeInput(this string input)
        {
            if (input == null)
                return String.Empty;

            const RegexOptions options = RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace |
                                         RegexOptions.Singleline | RegexOptions.IgnoreCase;

            var builder = Regex.Replace(input, @"(\s+) | (<br>)", " ", options).Trim().ToCharArray();

            var targetIndex = 0;
            var openBrackets = 0;

            for (var sourceIndex = 0; sourceIndex < builder.Length; sourceIndex++)
            {
                switch (builder[sourceIndex])
                {
                    case '[':
                        openBrackets++;
                        break;

                    case ']':
                        openBrackets = Math.Max(openBrackets - 1, 0);
                        break;

                    case '\r':
                    case '\n':
                    case '\v':
                    case '\t':
                    case ' ':
                        if (openBrackets == 0 && (targetIndex == 0 || builder[targetIndex - 1] != ' '))
                            builder[targetIndex++] = ' ';
                        break;

                    default:
                        if (openBrackets == 0)
                            builder[targetIndex++] = builder[sourceIndex].ReplaceWideWithLatin();
                        break;
                }
            }

            return new string(builder, 0, targetIndex);
        }
    }
}